using System.Collections.Generic;
using SqlQueryBuilder.Clauses;
using SqlQueryBuilder.Util;

namespace SqlQueryBuilder.Criterias
{
    /// <summary>
    /// Order by Criteria
    /// </summary>
    public class OrderBy : ICriteria
    {
        #region Properties

        /// <summary>
        /// Gets or sets the order by clauses.
        /// </summary>
        /// <value>The order by clauses.</value>
        public List<OrderByClause> Clauses { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="OrderBy"/> class.
        /// </summary>
        public OrderBy()
        {
            Clauses = new List<OrderByClause>();
        }

        #endregion
        
        /// <summary>
        /// Builds the criteria.
        /// </summary>
        /// <returns></returns>
        public string BuildCriteria()
        {
            if (Clauses.Count == 0) return string.Empty;

            bool firstClause = true;
            string orderby = string.Empty;

            foreach (OrderByClause orderByClause in Clauses)
            {
                foreach (var field in orderByClause.Fields)
                {
                    if (firstClause)
                        firstClause = false;
                    else
                        orderby = SqlMultipleFields.AddSeparator(orderby);

                    orderby += string.Format("{0} {1}", field, orderByClause.IsAscendant ? "" : "DESC");
                }
            }
            return string.Format("ORDER BY {0} ", orderby);
        }
    }
}